package com.sjx.jtt809.server.handler.initializer;

import com.sjx.jtt809.server.codec.DecoderJtt809;
import com.sjx.jtt809.server.codec.EncoderJtt809;
import com.sjx.jtt809.server.handler.SlaveLinkServerJtt809Handler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class SlaveLinkServerJtt809Initializer extends ChannelInitializer<SocketChannel> {

    private String ip;

    private int port;

    private int verifyCode;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getVerifyCode() {
        return verifyCode;
    }

    public void setVerifyCode(int verifyCode) {
        this.verifyCode = verifyCode;
    }

    public SlaveLinkServerJtt809Initializer(String ip, int port, int verifyCode) {
        this.ip = ip;
        this.port = port;
        this.verifyCode = verifyCode;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline channelPipeline = ch.pipeline();

        // 打印日志信息
        channelPipeline.addLast("loging", new LoggingHandler(LogLevel.INFO));

        // 解码 和 编码
        channelPipeline.addLast("decoder", new DecoderJtt809());
        channelPipeline.addLast("encoder", new EncoderJtt809());

        // 心跳检测
        channelPipeline.addLast("timeout", new IdleStateHandler(0, 140, 0, TimeUnit.SECONDS));

        // 客户端的逻辑
        channelPipeline.addLast("handler", new SlaveLinkServerJtt809Handler(ip, port, verifyCode));
    }
}